package com.cdy.grpcclient.service

import com.cdy.grpc.*
import io.grpc.Channel
import io.grpc.stub.StreamObserver
import net.devh.springboot.autoconfigure.grpc.client.GrpcClient
import org.springframework.stereotype.Service
import javax.xml.bind.JAXBElement

@Service
class StudentService {

    @GrpcClient("grpc-server")
    private lateinit var channel: Channel

    fun getStudent(name: String?): Student {
        val stub = StudentServiceGrpc.newBlockingStub(channel)
        return stub.getStudent(Request.newBuilder().setName(name).build())
    }

    fun getSameStudentList(name: String?): MutableIterator<Student>? {
        val stub = StudentServiceGrpc.newBlockingStub(channel)
        val sameStudentList = stub.getSameStudentList(Request.newBuilder().setName(name).build())
        sameStudentList.forEach {
            println(it.name + it.age)
        }
        return sameStudentList
    }

    fun getStudentRecord(name: MutableList<String>?): Response? {


        val stub = StudentServiceGrpc.newStub(channel)
        var response: Response? = null
        val responseObserver = object : StreamObserver<Response> {
            override fun onNext(value: Response?) {
                response = value!!
            }

            override fun onError(t: Throwable?) {
                t?.printStackTrace()
            }

            override fun onCompleted() {
                println("completed")
            }

        }
        val requestObserver = stub.getStudentRecord(responseObserver)
        name?.forEach {
            requestObserver.onNext(Request.newBuilder()
                    .setName(it).build())
        }

        requestObserver.onCompleted()
        Thread.sleep(1000)
        return response
    }

    fun getStudentRoster(name: MutableList<String>?): Response {


        val stub = StudentServiceGrpc.newStub(channel)
        var list = mutableListOf<Roster>()
        val responseObserver = object : StreamObserver<Roster> {
            override fun onNext(value: Roster?) {
                if (value!=null) {
                    list.add(value)
                }
            }

            override fun onError(t: Throwable?) {
                t?.printStackTrace()
            }

            override fun onCompleted() {
                println("completed")
            }

        }
        val requestObserver = stub.getStudentRoster(responseObserver)
        name?.forEach {
            requestObserver.onNext(Request.newBuilder()
                    .setName(it).build())
        }

        requestObserver.onCompleted()
        Thread.sleep(1000)
        return Response.newBuilder().addAllRoster(list).build()

    }


}